<?php

namespace App\Providers;

use App\Auth\User;
use App\Models\Token;
use App\Core\Enums\HeaderEnum;
use Illuminate\Auth\AuthManager;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Gate;
use Illuminate\Support\ServiceProvider;

class AuthServiceProvider extends ServiceProvider
{
    /**
     * Register any application services.
     *
     * @return void
     */
    public function register()
    {

    }

    /**
     * Boot the authentication services for the application.
     * @return void
     */
    public function boot()
    {
        $this->app['auth']->viaRequest('api', function ($request) {
            $token = (string)$request->header(HeaderEnum::AuthToken);
            if (empty($token)) {
                $token = (string)$request->cookie(strtolower(HeaderEnum::AuthToken));
            }
            if ($token) {
                $auth = Token::load($token);
                if(empty($auth)){
                    return null;
                }
                $uid = $auth->id();
                if (!empty($uid)) {
                    return User::query()->where('id', $uid)->first();
                }
            }
            return null;
        });
    }
}
